package com.gene.tlonpo.manager;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.gene.tlonpo.guard.Guard;
import com.gene.tlonpo.guard.interf.GuardI;
import com.gene.tlonpo.manager.interf.GuardManagerI;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

/**
 * 本地哨兵管理器
 * 单例
 *
 * @author gene
 */
public class GuardLocalManager implements GuardManagerI {

    public static final GuardLocalManager INSTANCE = new GuardLocalManager();

    /**
     * 哨兵管理
     * bizKey->guardId->guard
     */
    private static final ConcurrentHashMap<String, HashMap<String, Guard>> GUARD_MANAGE = new ConcurrentHashMap<>();

    private GuardLocalManager() {
    }

    @Override
    public void removeGuard(GuardI guardI) {
        if (!(guardI instanceof Guard)) {
            throw new RuntimeException(
                    "can not execute timeoutmanager,because of param type is not com.gene.tlonpo.guard.Guard");
        }
        Guard guard = (Guard) guardI;
        //移除
        HashMap<String, Guard> stringGuardHashMap = GUARD_MANAGE.get(guard.getBizKey());
        if (MapUtils.isEmpty(stringGuardHashMap)) {
            return;
        }

        stringGuardHashMap.remove(guard.getGuardId());
    }

    @Override
    public void addGuard(GuardI guardI) {
        if (!(guardI instanceof Guard)) {
            throw new RuntimeException(
                    "can not execute timeoutmanager,because of param type is not com.gene.tlonpo.guard.Guard");
        }
        Guard guard = (Guard) guardI;
        //添加到本地
        HashMap<String, Guard> stringGuardHashMap = GUARD_MANAGE.get(guard.getBizKey());
        if (MapUtils.isEmpty(stringGuardHashMap)) {
            stringGuardHashMap = Maps.newHashMap();
            GUARD_MANAGE.put(guard.getBizKey(), stringGuardHashMap);
        }

        stringGuardHashMap.put(guard.getGuardId(), guard);

    }

    @Override
    public <T extends GuardI> T getGuard(String bizKey, String guardId) {
        HashMap<String, Guard> stringGuardHashMap = GUARD_MANAGE.get(bizKey);
        return (T) stringGuardHashMap.get(guardId);
    }

    @Override
    public <T extends GuardI> List<T> getGuard(String bizKey) {
        HashMap<String, Guard> stringGuardHashMap = GUARD_MANAGE.get(bizKey);
        if (stringGuardHashMap == null || CollectionUtils.isEmpty(stringGuardHashMap.values())) {
            return null;
        }
        return stringGuardHashMap.values().stream().map(g -> (T) g).collect(Collectors.toList());
    }
}
